package com.shuqi.activity;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.RechargesAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.StringUtils;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.controller.RechargesController;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.ItemInfo;
import com.shuqi.model.bean.RechargesHistosyData;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 充值记录Activity
 * 
 * @author zhuchen
 * 
 */
public class RechargesActivity extends ActivityBase implements IEventListener,
        HttpRequestErrListener, OnClickListener {

    private final int init = EventTypeConstants.BASE;

    private final int initsuccess = init + 1;

    private final int init_error = initsuccess + 1;
    private final int loadmore_error = init_error + 1;

    private RechargesController controller;

    /** 充值记录列表 */
    private ListView act_recharges_list;

    /** 充值记录数据 */
    private RechargesHistosyData rechargesdata;

    private RechargesAdapter adapter;

    private LinearLayout act_recharges_null;// 无充值记录

    private MyListFooter listFooter;

    private Intent intent;

    private int totalCount;// 总页数

    private int pageIndex = 1; // 请求页

    private LinearLayout err404;// 无网络

    private LinearLayout layoutLoading;// 进度圈

    private TextView retry; // 重试

    private List<ItemInfo> list;
    List<ItemInfo> templist;

    private TextView tvHint;

    private CommonTitle mTitle;
    private ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case initsuccess:
                    activityInitData();
                    break;
                case init_error:
                    layoutLoading.setVisibility(View.GONE);
                    act_recharges_null.setVisibility(View.GONE);
                    findViewById(R.id.include_error).setVisibility(View.VISIBLE);
                    break;
                case loadmore_error:
                    layoutLoading.setVisibility(View.GONE);
                    listFooter.loadingError();
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (controller == null) {
            controller =
                    (RechargesController) MainController.getMainManagerInstance().createController(
                            MainController.CONTROLLER_ID_RECHARGES, this);
        }
        controller.addEventListener(this);


        super.onCreate(savedInstanceState);

        setContentView(R.layout.act_recharges);

        handler.sendEmptyMessage(init);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                this.pageIndex++;
                rechargesdata = (RechargesHistosyData) data;
                if (rechargesdata != null) {
                    if (!TextUtils.isEmpty(rechargesdata.getTotalCount())) {
                        totalCount = Integer.parseInt(rechargesdata.getTotalCount());
                    }
                    templist = rechargesdata.getList();
                    if (list == null) {
                        list = templist;
                    } else {
                        this.list.addAll(templist);
                    }
                }
                handler.sendEmptyMessage(initsuccess);
                break;
            default:
                if (list == null) {
                    handler.sendEmptyMessage(init_error);
                } else {
                    handler.sendEmptyMessage(loadmore_error);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        StatisticsUtils.onEvent(this, StatisticsEventID.ACCOUNT_RECHARGES);
        super.onResume();
    }

    @Override
    public void activityLogicForward() {
        tvHint = (TextView) findViewById(R.id.tv_hint);
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);

        findViewById(R.id.act_gorecharges).setOnClickListener(this);
        this.layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        this.err404 = (LinearLayout) findViewById(R.id.include_error);
        this.act_recharges_list = (ListView) findViewById(R.id.act_recharges_list);

        MyFooterListener listener = new MyFooterListener() {
            @Override
            public void reload() {
                controller.handle(0, "" + pageIndex); 
                listFooter.loadingStart();
            }

            @Override
            public void loadNext() {
                controller.handle(0, "" + pageIndex); 
                listFooter.loadingStart();
            }

            @Override
            public boolean hasNext() {
                if (list == null) {
                    return false;
                }
                return (list.size() < totalCount) || (list != null && templist == null);
            }
        };
        listFooter = new MyListFooter(this, listener);
        act_recharges_list.addFooterView(listFooter);

        this.layoutLoading = (LinearLayout) findViewById(R.id.include_loading);

        this.act_recharges_null = (LinearLayout) findViewById(R.id.act_recharges_null);
        this.retry = (TextView) err404.findViewById(R.id.retry);
        this.retry.setOnClickListener(this);

        this.adapter = new RechargesAdapter(this);
        act_recharges_list.setAdapter(adapter);

        this.requestAppList();
        listFooter.loadingStart();

        this.act_recharges_null.setVisibility(View.GONE);
    }

    @Override
    public void activityInitData() {
        layoutLoading.setVisibility(View.GONE);
        act_recharges_list.setVisibility(View.VISIBLE);

        if (rechargesdata != null && rechargesdata.getList() != null
                && rechargesdata.getList().size() > 0) {
            if (StringUtils.isNotBlank(rechargesdata.getHint())) {
                tvHint.setVisibility(View.VISIBLE);
                tvHint.setText(rechargesdata.getHint());
            }

            adapter.setList(list);
            adapter.notifyDataSetChanged();
            err404.setVisibility(View.GONE);
        } else {
            tvHint.setVisibility(View.GONE);
            // 无充值
            act_recharges_list.setVisibility(View.GONE);
            act_recharges_null.setVisibility(View.VISIBLE);
            err404.setVisibility(View.GONE);
            return;
        }

        totalCount = Integer.parseInt(rechargesdata.getTotalCount());
        listFooter.loadingSuccess();
    }

    // 按钮点击事件处理
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.act_gorecharges:
                intent = new Intent(this, PayActivity.class);
                ActivityManager.getInstance().startNextActivity(intent, this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                }
//                this.requestAppList();
//                act_recharges_null.setVisibility(View.GONE);
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        requestAppList();
                        act_recharges_null.setVisibility(View.GONE);

                    }
                });
                break;
            default:
                break;
        }

    }

    /** 翻页加载请求 */
    private void requestAppList() {
        layoutLoading.setVisibility(View.VISIBLE);
        err404.setVisibility(View.GONE);
        controller.handle(0, "" + pageIndex); 
    }


    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
